<template>
  <div class="middle">
    <div class="area-selector-container">
      <el-select v-model="state.groupId" clearable placeholder="请选择分组" @change="handleGroup()">
        <el-option v-for="item in groupOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button :disabled="!state.groupId" @click="handleOperate" v-hasPermi="['iot:deviceGroup:ctrl']">控制</el-button>
      <el-button @click="refresh">刷新</el-button>
    </div>
  </div>
  <swSlGroup ref="sw_sl_groupRef" />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getDeviceGroupsList } from '@/views/setting/device/api/devices.api'
import swSlGroup from '@/views/setting/device/components/sw_sl_group.vue'
// 引入公共方法判断是否是灯控设备
import { isLightController } from '@/utils/deviceUtils'

const state = reactive({
  groupId: ''
})

const emit = defineEmits(['group-selected'])

const handleGroup = () => {
  emit('group-selected', state.groupId || '')
}

const refresh = () => {
  handleGroup()
}

/** 控制按钮操作 */
const sw_sl_groupRef = ref()
const handleOperate = () => {
  if (!state.groupId) return
  
  const selectedGroup = groupOptions.value.find(group => group.id === state.groupId)
  if (!selectedGroup || !selectedGroup.product) return

  console.log('selectedGroup', selectedGroup)

  if (isLightController(selectedGroup.product.productKey)) {
    sw_sl_groupRef.value.openDialog(selectedGroup)
  }
}

// 分组字典
const groupOptions = ref<any[]>([])
// 获取分组下拉框数据
const getGroupsList = () => {
  getDeviceGroupsList({ pageNum: 1, pageSize: 99999, name: '' }).then((res) => {
    groupOptions.value = res.data.rows
  })
}
onMounted(() => {
  getGroupsList()
})
</script>

<style lang="scss" scoped>
.middle {
  width: 100%; // 让 middle 元素宽度占满父容器
  box-sizing: border-box; // 确保内边距和边框包含在宽度内
  position: relative;
  display: flex;
  justify-content: center; // 水平居中内容
  align-items: center; // 垂直居中内容
  z-index: 11;
  padding: 10px 0; // 根据需要调整内边距
  height: 34px;
}
.area-selector-container {
  margin: 1px 0 3px 30%;
  position: absolute;
  left: 15px;
  z-index: 100;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .el-button {
    margin-left: 10px; 
  }
}
</style>
